package o2o.postman.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.order.OrderPayMemory;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.order.OrderPostmanInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.postman.mapper.CityPostmanMapper;
import o2o.postman.model.CityPostman;
import o2o.postman.service.PostmanService;
import o2o.system.data.SYS_CONFIG_PATH;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author: guo_wei
 * @Date: 2021-06-04
 * @Description: 骑手报表服务实现
 */
@Service
public class PostmanServiceImpl extends ServiceImpl<CityPostmanMapper, CityPostman> implements PostmanService {

    /**
     * 配送员接单或拒绝接单
     */
    @Override
    public ResultInfo postmanSureOrRefuse(String orderNo, String username, Integer isSure) {
        ValidateUtil.validate("信息不完整，请稍后再试", orderNo, username);
        ValidateUtil.validate("请选择操作类型，请稍后再试", isSure);
        ValidateUtil.validate("操作类型不正确，请稍后再试", 0 == isSure);
        // 获取骑手
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(username);
        ValidateUtil.validate("您无权操作", postman);
        // 查询订单
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        ValidateUtil.validate("订单不存在，请稍后再试", orderInfo);
        ValidateUtil.validate("该订单未发起转单", orderInfo.getChangePostman());
        ValidateUtil.validate("您不是被转对象无法操作", !username.equalsIgnoreCase(orderInfo.getChangePostman()));
        // 查询UserInfo
        String oldPostman = orderInfo.getPostManUsername();
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        ValidateUtil.validate("当前用户信息有误", userInfo);
        Connection co = null;
        // 事务
        try {
            co = UserDaoSql.getInstance().getConnection(true);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo("数据库连接异常");
        }
        //todo 每日可转单数
        //更新转单信息
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.ORDER_POSTMAN).append(" set isSure = ").append(isSure).append(",sureTime=").append(DateUtils.getCurrTime())
                .append(",updateUser='").append(username).append("' where orderNo = '").append(orderNo)
                .append("' and delFlag = 0 and isSure = 0 and toUsername = '").append(username).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString(), co);
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(co);
            UserDaoSql.getInstance().close(co);
            return new ResultInfo("接单失败，请稍后再试");
        }
        switch (isSure) {
            case OrderPostmanInfo.SURE: {//接单
                String phone = userInfo.getTelPhone();
                if (ValidateUtil.isNull(phone)) {
                    phone = username;
                }
                String poto = userInfo.getSignPhoto();
                if (ValidateUtil.isNotNull(poto) && ValidateUtil.isNetUrl(poto)) {
                    poto = poto.replace(SYS_CONFIG_PATH.IMAGE_BASE_URL, "");
                }
                //删除订单中的正在转单人
                StringBuffer sbOrder = new StringBuffer();
                sbOrder.append("update ").append(PojoTables.OrderInfo).append(" set postmanUsername='").append(username)
                        .append("',postmanName='").append(userInfo.getName()).append("',postmanPhone='").append(phone)
                        .append("',postmanImageUrl='").append(poto).append("',changePostman=null,changePostmanTime=NULL,updateUser='").append(username)
                        .append("' where delFlag = 0 and orderNo = '").append(orderNo).append("'");
                boolean isUpdatePayInfo = false;
                try {
                    UserDaoSql.getInstance().executeBySql(sbOrder.toString(), co);

                    co.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    UserDaoSql.getInstance().rollback(co);
                    return new ResultInfo("接单失败，请稍后再试.");
                } finally {
                    UserDaoSql.getInstance().close(co);
                }
                OrderInfoMemory.getInstance().modifyStatus(orderNo);//更新订单信息
                // 更新订单的信息
                if (isUpdatePayInfo) {
                    OrderPayMemory.getInstance().modify(orderNo);
                    try {
                        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
                        JmsSender.setTopicSender(notify);
                    } catch (Exception e) {
                    }
                }
                //删除之前配送员订单列表里的该订单
                OrderInfoMemory.getInstance().removePostmanOrderInfo(oldPostman, orderNo);
            }
            break;
            case OrderPostmanInfo.REFUSE: {//拒绝接单
                //删除订单中的正在转单人
                StringBuffer sbOrder = new StringBuffer();
                sbOrder.append("update ").append(PojoTables.OrderInfo).append(" set changePostman=null,changePostmanTime=null,updateUser='").append(username)
                        .append("' where delFlag = 0 and orderNo = '").append(orderNo).append("'");

                try {
                    UserDaoSql.getInstance().executeBySql(sbOrder.toString(), co);
                    co.commit();
                } catch (SQLException e) {
                    e.printStackTrace();
                    UserDaoSql.getInstance().rollback(co);
                    return new ResultInfo("接单失败，请稍后再试.");
                } finally {
                    UserDaoSql.getInstance().close(co);
                }
                OrderInfoMemory.getInstance().modifyStatus(orderNo);//更新订单信息
                // 删除转单订单
                OrderInfoMemory.getInstance().postmanRefuseChangeOrder(username, orderNo);
            }
            break;
        }
        return new ResultInfo();
    }
}
